package com.technician.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.technician.common.DeleteRequest;
import com.technician.common.ResponseResult;
import com.technician.exceptionHandler.GlobalSystemException;
import com.technician.model.dto.user.*;
import com.technician.model.entity.User;
import com.technician.model.enums.HttpStatusEnum;
import com.technician.model.security.LoginUser;
import com.technician.model.vo.UserVO;
import com.technician.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 用户登录接口
     *
     * @param userLoginRequest 传入账号，密码
     * @return 返回基本用户信息 和 token
     */
    @PostMapping("/login")
    public ResponseResult login(@RequestBody @Validated UserLoginRequest userLoginRequest) {
        return userService.login(userLoginRequest);
    }

    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public ResponseResult register(@RequestBody @Validated UserRegisterRequest userRegisterRequest) {
        return userService.register(userRegisterRequest);
    }

    /**
     * 获取当前登录信息(已经经过 jwt 过滤器判断token是否过期)
     *
     * @return
     */
    @GetMapping("/get/login")
    public ResponseResult<UserVO> getLoginUser() {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (loginUser == null) {
            throw new GlobalSystemException(401,"用户未登录");
        }
        UserVO userVO = UserVO.objToVo(loginUser.getUser());
        return ResponseResult.success(userVO);
    }

    /**
     * 查询用户列表 （管理员）
     *
     * @param userQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @PreAuthorize("hasAuthority('system:user:list')")
    public ResponseResult<Page<User>> listUserByPage(@RequestBody UserQueryRequest userQueryRequest) {
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        Page<User> userPage = userService.page(new Page<>(current, size),
                userService.getQueryWrapper(userQueryRequest));
        return ResponseResult.success(HttpStatusEnum.SUCCESS_RESPONSE, userPage);
    }

    /**
     * 根据 id 获取 用户信息 （管理员）
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    @PreAuthorize("hasAuthority('system:user:list')")
    public ResponseResult<User> getUserById(@RequestParam Long id) {
        if (id < 0) {
            throw new GlobalSystemException(400,"请求参数异常");
        }
        User user = userService.getById(id);
        if (user == null) {
            throw new GlobalSystemException(400,"账号不存在");
        }
        return ResponseResult.success(user);
    }

    /**
     * 根据 id 获取 用户信息
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public ResponseResult<UserVO> getUserVOById(@RequestParam Long id) {
        ResponseResult<User> user = getUserById(id);
        return ResponseResult.success(UserVO.objToVo(user.getData()));
    }

    /**
     * 删除一个用户 （管理员）
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('system:user:list')")
    public ResponseResult<Boolean> deleteUserById(@RequestBody @Validated DeleteRequest deleteRequest) {
        boolean b = userService.removeById(deleteRequest.getId());
        if (!b){
            return ResponseResult.error(400001,"删除失败");
        }
        return ResponseResult.success(HttpStatusEnum.SUCCESS_RESPONSE);
    }

    /**
     * 修改一个用户 （管理员）
     *
     * @param updateRequest
     * @return
     */
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('system:user:list')")
    public ResponseResult<Boolean> updateUserById(@RequestBody @Validated UserUpdateRequest updateRequest) {
        User user = new User();
        String password = updateRequest.getPassword();
        BeanUtils.copyProperties(updateRequest,user,"password");
        if (StrUtil.isNotBlank(password)){
            // 加密密码
            user.setPassword(passwordEncoder.encode(password));
        }
        boolean b = userService.updateById(user);
        if (!b){
            return ResponseResult.error(400001,"修改失败");
        }
        return ResponseResult.success(HttpStatusEnum.SUCCESS_RESPONSE);
    }

    /**
     * 修改一个用户
     *
     * @param updateRequest
     * @return
     */
    @PostMapping("/update/my")
    public ResponseResult<Boolean> updateUserById(@RequestBody @Validated UpdateMyUserRequest updateRequest) {
        // 获取当前登录用户
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long id = loginUser.getUser().getId();
        User user = new User();
        BeanUtils.copyProperties(updateRequest,user);
        user.setId(id);
        boolean b = userService.updateById(user);
        if (!b){
            return ResponseResult.error(400001,"修改失败");
        }
        return ResponseResult.success(HttpStatusEnum.SUCCESS_RESPONSE);
    }
}